/* Ping Server. 
 * This service implements a simple ping server 
 * 
 * Created:
 *   by Nikhil Handigol
 */

#include "inc.h"	/* include master header file */
#include <minix/endpoint.h>
#include <minix/syslib.h>
#include <minix/com.h>

/* Allocate space for the global variables. */
endpoint_t who_e;	/* caller's proc number */
int callnr;		/* system call number */
int sys_panic;		/* flag to indicate system-wide panic */
extern int errno;	/* error number set by system library */

FORWARD _PROTOTYPE(void get_work, (message *m_ptr)			);
FORWARD _PROTOTYPE(void reply, (int whom, message *m_ptr)		);
/*===========================================================================*
 *				main                                         *
 *===========================================================================*/
PUBLIC int main(int argc, char **argv)
{
/* This is the main routine of this service. 
 */
  message m, m1;
  int result;                 
  sigset_t sigset;

  /* Main loop - get work and do it, forever. */         
  while (TRUE) {              

      /* Wait for incoming message, sets 'callnr' and 'who'. */
      get_work(&m);
      /*printf("PINGPONG: received PING, sending PONG\n");*/

      switch (callnr) {
      case PING:
	  result = PONG;
          break;
      default: 
          report("PINGS","warning, got illegal request from:", m.m_source);
          result = EINVAL;
      }

      /* Finally send reply message, unless disabled. */
      if (result == PONG) {
	  read_tsc((u32_t*)&m.m1_i2, (u32_t*)&m.m1_i3);
          m.m_type = result;  		/* build reply message */
	  reply(who_e, &m);		/* send it away */
	  if(m.m1_i1 == 1) {
	      m1.m1_i1 = SYSCTL_CODE_FLUSH_IPC;
	      _taskcall(SYSTASK, SYS_SYSCTL, &m1);
	  }
      }
  }
  return(OK);				/* shouldn't come here */
}

/*===========================================================================*
 *				get_work                                     *
 *===========================================================================*/
PRIVATE void get_work(m_ptr)
message *m_ptr;				/* message buffer */
{
    int status = 0;
    status = receive(ANY, m_ptr);   /* this blocks until message arrives */
    if (OK != status)
        panic("PINGS","failed to receive message!", status);
    who_e = m_ptr->m_source;        /* message arrived! set sender */
    callnr = m_ptr->m_type;       /* set function call number */
}

/*===========================================================================*
 *				reply					     *
 *===========================================================================*/
PRIVATE void reply(who_e, m_ptr)
int who_e;                           	/* destination */
message *m_ptr;				/* message buffer */
{
    int s;
    s = send(who_e, m_ptr);    /* send the message */
    if (OK != s)
        printf("PINGS: unable to send reply to %d: %d\n", who_e, s);
}

